package cn.it58.gooditname.services

import com.google.gson.Gson
import com.google.gson.JsonObject
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.components.Service
import org.apache.http.client.methods.HttpPost
import org.apache.http.entity.StringEntity
import org.apache.http.impl.client.HttpClients
import org.apache.http.util.EntityUtils
import java.nio.charset.StandardCharsets

@Service
class TranslationService {

    private val gson = Gson()
    private val localDictionary = LocalDictionary()

    companion object {
        fun getInstance(): TranslationService {
            return ApplicationManager.getApplication().getService(TranslationService::class.java)
        }
    }

    /**
     * 翻译中文为英文并转换为指定格式
     */
    fun translate(chineseText: String, format: NamingFormat): String {
        val englishText = translateToEnglish(chineseText)
        return convertToFormat(englishText, format)
    }

    /**
     * 将中文翻译为英文
     */
    private fun translateToEnglish(chineseText: String): String {
        val configService = ConfigService.getInstance()
        val apiKey = configService.getApiKey()

        // 如果配置了API密钥，优先使用AI翻译
        if (apiKey.isNotBlank()) {
            val aiResult = translateWithApi(chineseText, apiKey, configService.getAiModel())
            if (aiResult != null) {
                return aiResult
            }
        }

        // 回退到本地词典
        return localDictionary.translate(chineseText)
    }

    /**
     * 使用轨迹流动API翻译
     */
    private fun translateWithApi(chineseText: String, apiKey: String, model: String): String? {
        return try {
            HttpClients.createDefault().use { httpClient ->
                val httpPost = HttpPost("https://api.siliconflow.cn/v1/chat/completions")

                // 设置请求头
                httpPost.setHeader("Content-Type", "application/json")
                httpPost.setHeader("Authorization", "Bearer $apiKey")

                // 构建请求体
                val requestBody = JsonObject().apply {
                    addProperty("model", model)
                    addProperty("max_tokens", 100)
                    addProperty("temperature", 0.1)

                    // 构建消息
                    val message = JsonObject().apply {
                        addProperty("role", "user")
                        addProperty("content", buildPrompt(chineseText))
                    }

                    add("messages", gson.toJsonTree(arrayOf(message)))
                }

                // 设置请求体
                val entity = StringEntity(requestBody.toString(), StandardCharsets.UTF_8)
                httpPost.entity = entity

                // 执行请求
                httpClient.execute(httpPost).use { response ->
                    val responseEntity = response.entity
                    if (responseEntity != null) {
                        val responseStr = EntityUtils.toString(responseEntity, StandardCharsets.UTF_8)
                        parseApiResponse(responseStr)
                    } else {
                        null
                    }
                }
            }
        } catch (e: Exception) {
            e.printStackTrace()
            null
        }
    }

    /**
     * 构建AI提示词
     */
    private fun buildPrompt(chineseText: String): String {
        return "请将以下中文翻译为英文，只返回翻译结果，不要包含其他内容：$chineseText"
    }

    /**
     * 解析API响应
     */
    private fun parseApiResponse(responseStr: String): String? {
        return try {
            val response = gson.fromJson(responseStr, JsonObject::class.java)
            if (response.has("choices") && response.getAsJsonArray("choices").size() > 0) {
                val choice = response.getAsJsonArray("choices")[0].asJsonObject
                if (choice.has("message")) {
                    val message = choice.getAsJsonObject("message")
                    if (message.has("content")) {
                        return message.get("content").asString.trim()
                    }
                }
            }
            null
        } catch (e: Exception) {
            e.printStackTrace()
            null
        }
    }

    /**
     * 转换为指定命名格式
     */
    private fun convertToFormat(englishText: String, format: NamingFormat): String {
        if (englishText.isBlank()) {
            return englishText
        }

        // 清理文本，移除标点符号
        val cleanText = englishText.replace(Regex("[^a-zA-Z\\s]"), "").trim()

        // 按空格分割单词
        val words = cleanText.split(Regex("\\s+")).filter { it.isNotBlank() }

        return when (format) {
            NamingFormat.CAMEL_CASE -> toCamelCase(words)
            NamingFormat.PASCAL_CASE -> toPascalCase(words)
            NamingFormat.SNAKE_CASE -> toSnakeCase(words)
            NamingFormat.KEBAB_CASE -> toKebabCase(words)
        }
    }

    /**
     * 转换为驼峰命名
     */
    private fun toCamelCase(words: List<String>): String {
        if (words.isEmpty()) return ""
        
        return buildString {
            append(words[0].lowercase())
            for (i in 1 until words.size) {
                append(words[i].capitalize())
            }
        }
    }

    /**
     * 转换为大驼峰命名
     */
    private fun toPascalCase(words: List<String>): String {
        return words.joinToString("") { it.capitalize() }
    }

    /**
     * 转换为下划线命名
     */
    private fun toSnakeCase(words: List<String>): String {
        return words.joinToString("_") { it.lowercase() }
    }

    /**
     * 转换为短横线命名
     */
    private fun toKebabCase(words: List<String>): String {
        return words.joinToString("-") { it.lowercase() }
    }

    /**
     * 首字母大写
     */
    private fun String.capitalize(): String {
        return if (this.isEmpty()) this else this.first().uppercaseChar() + this.substring(1).lowercase()
    }
} 